package com.imooc.common._this;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 可以实现对指定网段的IP地址进行ping测试
 */
public class Ping {
    public static void main(String[] args) {
        Ping p = new Ping();
        List<String> strings = FileUtil.readLines("/Users/dengwubo/IdeaProjects/boob/common/src/main/resources/ip.txt", "utf-8");
        for (String string : strings) {
            if(!StrUtil.startWith(string,"192")){
                p.ping(string);

            }
        }
    }
    boolean ping(String ip) {
        // 前缀根据自己需求调整
        String ins = "ping " + ip;

        try {
            Process p = Runtime.getRuntime().exec(ins);
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.indexOf("bytes from") != -1) { //这里不同的cmd可能不一样
//                    System.out.println(ip + " 连接成功");
                    return true;
                }
                if (line.indexOf("Request timeout") != -1) { //这里也是
                    System.out.println(ip + "");
                    return false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
